package com.neulogistics.contrib.warehouse.api.application.command.handler;

import com.blackto.lib.mediat.unicast.IRequestHandler;
import com.neulogistics.contrib.warehouse.api.application.command.PurchaseCommand;
import com.neulogistics.contrib.warehouse.api.application.rpc.IWarehouseRPC;
import com.neulogistics.contrib.warehouse.domain.model.aggregate.CirculationOrder;
import com.neulogistics.contrib.warehouse.domain.model.enumeration.CirculationDetail;
import com.neulogistics.contrib.warehouse.domain.model.enumeration.CirculationType;
import com.neulogistics.contrib.warehouse.domain.model.valueobject.GoodsItem;
import com.neulogistics.contrib.warehouse.domain.repository.ICirculationOrderRepository;
import com.neulogistics.infrastructure.cache.idservice.RedisIdUtil;
import com.neulogistics.infrastructure.common.serviceresult.BaseResponse;
import com.neulogistics.infrastructure.common.serviceresult.ResultUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;

@Component
public class PurchaseCommandHandler implements IRequestHandler<PurchaseCommand, BaseResponse<Boolean>> {
    @Resource
    private ICirculationOrderRepository circulationOrderRepository;

    @Resource
    private IWarehouseRPC warehouseRPC;

    @Resource
    private RedisIdUtil redisIdUtil;


    private final String CirculationOrder_Id_Key;

    public PurchaseCommandHandler(@Value("${spring.application.name}") String appName) {
        CirculationOrder_Id_Key = appName + ":" + "circulationOrderId";
    }


    @Override
    public BaseResponse<Boolean> handle(PurchaseCommand command) {
        // 远程调用采购中心进货接口
        Boolean success = warehouseRPC.purchase(command);

        // 生成进货入库单
        if(success){
            Long circulationId = redisIdUtil.nextId(CirculationOrder_Id_Key);
            GoodsItem goodsItem = new GoodsItem(command.goodsId, command.goodsName, command.count, command.measureUnit);
            List<GoodsItem> goodsItems = Arrays.asList(goodsItem);
            CirculationOrder circulationOrder = new CirculationOrder(
                    circulationId, command.warehouseId, CirculationType.Inbound,
                    CirculationDetail.Purchase_Inbound, null, goodsItems);

            circulationOrderRepository.save(circulationOrder);
        }

        return ResultUtils.success(Boolean.TRUE);
    }
}
